package com.txsj.scan.test;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.nativec.tools.ModuleManager;
import com.txsj.scan.base.BaseActivity;
import com.txsj.scan.MyApplication;
import com.txsj.scan.R;
import com.txsj.scan.base.BasePresenter;
import com.txsj.scan.reader.base.ReaderBase;
import com.txsj.scan.reader.helper.ISO180006BOperateTagBuffer;
import com.txsj.scan.reader.helper.InventoryBuffer;
import com.txsj.scan.reader.helper.OperateTagBuffer;
import com.txsj.scan.reader.helper.ReaderHelper;
import com.txsj.scan.reader.helper.ReaderSetting;
import com.txsj.scan.reader.tools.ExcelUtils;
import com.txsj.scan.reader.widget.TagRealList;

public class ReadScanActivity extends BaseActivity {

    private ReaderBase mReader;
    private ReaderHelper mReaderHelper;
    public static boolean mIsMonitorOpen = false;

    public static Activity activity ;

    private static ReaderSetting m_curReaderSetting;
    private static InventoryBuffer m_curInventoryBuffer;
    private static OperateTagBuffer m_curOperateTagBuffer;
    private static ISO180006BOperateTagBuffer m_curOperateTagISO18000Buffer;
    public static int mSaveType = 0;

    private TextView mStartStop,mTagsSpeedText, mTagsTimeText, mTagsOpTimeText,mTagsCountText,mTagsTotalText,save_to_sql,query_from_sql;
    private TagRealList mTagRealList;

    private LocalBroadcastManager lbm;
    private boolean bTmpInventoryFlag = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_read);

        MyApplication.getInstance().addActivity(this);
        activity = this;

        initView();

        // Storage Permissions
        ExcelUtils.verifyStoragePermissions(this);

        try {
            mReaderHelper = ReaderHelper.getDefaultHelper();
            mReader = mReaderHelper.getReader();
        } catch (Exception e) {
            return;
        }

        m_curReaderSetting = mReaderHelper.getCurReaderSetting();
        m_curInventoryBuffer = mReaderHelper.getCurInventoryBuffer();
        m_curOperateTagBuffer = mReaderHelper.getCurOperateTagBuffer();
        m_curOperateTagISO18000Buffer = mReaderHelper.getCurOperateTagISO18000Buffer();

        lbm = LocalBroadcastManager.getInstance(this);

        IntentFilter itent = new IntentFilter();
        itent.addAction(ReaderHelper.BROADCAST_REFRESH_FAST_SWITCH);
        itent.addAction(ReaderHelper.BROADCAST_REFRESH_INVENTORY);
        itent.addAction(ReaderHelper.BROADCAST_REFRESH_INVENTORY_REAL);
        itent.addAction(ReaderHelper.BROADCAST_REFRESH_ISO18000_6B);
        itent.addAction(ReaderHelper.BROADCAST_REFRESH_OPERATE_TAG);
        itent.addAction(ReaderHelper.BROADCAST_REFRESH_READER_SETTING);
        itent.addAction(ReaderHelper.BROADCAST_WRITE_LOG);
        itent.addAction(ReaderHelper.BROADCAST_WRITE_DATA);

        lbm.registerReceiver(mRecv, itent);
    }

    @Override
    protected BasePresenter providePresenter() {
        return null;
    }

    private void initView() {
        mStartStop = (TextView) findViewById(R.id.startstop);
        mTagsCountText = (TextView) findViewById(R.id.tags_count_text);
        mTagsTotalText = (TextView) findViewById(R.id.tags_total_text);
        mTagsSpeedText = (TextView) findViewById(R.id.tags_speed_text);
        mTagsTimeText = (TextView) findViewById(R.id.tags_time_text);
        mTagsOpTimeText = (TextView) findViewById(R.id.tags_op_time_text);
        save_to_sql = (TextView) findViewById(R.id.save_to_sql);
        query_from_sql = (TextView) findViewById(R.id.query_from_sql);
        mTagRealList = (TagRealList) findViewById(R.id.tag_real_list);
        save_to_sql.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                saveToSql();
            }
        });
        query_from_sql.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                queryFromSql();
            }
        });
        mStartStop.setOnClickListener(setInventoryRealOnClickListener);
    }

    /**
     * 保存到数据库
     */
    private void saveToSql() {
        mTagRealList.saveDataToSql();
    }

    /**
     * 从数据库获取数据并打印
     */
    private void queryFromSql() {
        mTagRealList.queryDataFromSql();
    }

    private View.OnClickListener setInventoryRealOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            if (arg0.getId() == R.id.startstop) {
                startstop();
            }
        }
    };

    public void refresh(View view) {
        m_curInventoryBuffer.clearInventoryRealResult();
        refreshList();
        refreshText();
        clearText();
    }

    private void clearText() {
        mReaderHelper.setInventoryTotal(0);
        mTagsCountText.setText("0");
        mTagsTotalText.setText("0");
        mTagsSpeedText.setText("0");
        mTagsTimeText.setText("0");
        mTagsOpTimeText.setText("0");
        mTagRealList.clearText();
    }

    private void startstop() {
        bTmpInventoryFlag = false;

        m_curInventoryBuffer.clearInventoryPar();

        m_curInventoryBuffer.lAntenna.add((byte) 0x00);

        if (m_curInventoryBuffer.lAntenna.size() <= 0) {
            Toast.makeText(activity,
                    getResources().getString(R.string.antenna_empty),
                    Toast.LENGTH_SHORT).show();
            return;
        }

        m_curInventoryBuffer.bLoopInventoryReal = true;
        m_curInventoryBuffer.btRepeat = 0;

        String strRepeat = "1";
        if (strRepeat == null || strRepeat.length() <= 0) {
            Toast.makeText(activity,
                    getResources().getString(R.string.repeat_empty),
                    Toast.LENGTH_SHORT).show();
            return;
        }

        m_curInventoryBuffer.btRepeat = (byte) Integer.parseInt(strRepeat);

        if ((m_curInventoryBuffer.btRepeat & 0xFF) <= 0) {
            Toast.makeText(activity,
                    getResources().getString(R.string.repeat_min),
                    Toast.LENGTH_SHORT).show();
            return;
        }

        m_curInventoryBuffer.bLoopCustomizedSession = false;


        {
            if (!mStartStop.getText().toString()
                    .equals(getResources().getString(R.string.start_inventory))) {
                refreshText();
                mReaderHelper.setInventoryFlag(false);
                m_curInventoryBuffer.bLoopInventoryReal = false;

                refreshStartStop(false);
                mLoopHandler.removeCallbacks(mLoopRunnable);
                mHandler.removeCallbacks(mRefreshRunnable);
                refreshList();
                return;
            } else {
                refreshStartStop(true);
            }
        }

        // start_fixed by lei.li 2016/11/04 problem
        // m_curInventoryBuffer.clearInventoryRealResult();
        mReaderHelper.setInventoryFlag(true);
        // end_fixed by lei.li 2016/11/04

        mReaderHelper.clearInventoryTotal();
        refreshText();

        byte btWorkAntenna = m_curInventoryBuffer.lAntenna
                .get(m_curInventoryBuffer.nIndexAntenna);
        if (btWorkAntenna < 0)
            btWorkAntenna = 0;
        mReaderHelper.runLoopInventroy();
        m_curReaderSetting.btWorkAntenna = btWorkAntenna;
        refreshStartStop(true);
        mLoopHandler.removeCallbacks(mLoopRunnable);
        mLoopHandler.postDelayed(mLoopRunnable, 2000);
        mHandler.removeCallbacks(mRefreshRunnable);
        mHandler.postDelayed(mRefreshRunnable, 2000);
    }

    @SuppressWarnings("deprecation")
    private void refreshStartStop(boolean start) {
        if (start) {
            mStartStop.setText(getResources()
                    .getString(R.string.stop_inventory));
        } else {
            mStartStop.setText(getResources().getString(
                    R.string.start_inventory));
        }
    }

    private Handler mUpdateViewHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            refreshText();
            refreshList();
        }
    };

    private Handler mHandler = new Handler();
    private Runnable mRefreshRunnable = new Runnable() {
        public void run() {
            refreshList();
            mHandler.postDelayed(this, 2000);
        }
    };
    private Handler mLoopHandler = new Handler();
    private Runnable mLoopRunnable = new Runnable() {
        public void run() {
            /*
             * byte btWorkAntenna =
             * m_curInventoryBuffer.lAntenna.get(m_curInventoryBuffer
             * .nIndexAntenna); if (btWorkAntenna < 0) btWorkAntenna = 0;
             * mReader.setWorkAntenna(m_curReaderSetting.btReadId,
             * btWorkAntenna);
             */
            mReaderHelper.runLoopInventroy();
            mLoopHandler.postDelayed(this, 2000);
        }
    };


    private void refreshList() {
        mTagRealList.refreshList();
    }

    private void refreshText() {
        mTagsCountText.setText(String.valueOf(m_curInventoryBuffer.lsTagList
                .size()));
        mTagsTotalText
                .setText(String.valueOf(mReaderHelper.getInventoryTotal()));
        mTagsSpeedText.setText(String.valueOf(m_curInventoryBuffer.nReadRate));

        mTagsTimeText.setText(String
                .valueOf(m_curInventoryBuffer.dtEndInventory.getTime()
                        - m_curInventoryBuffer.dtStartInventory.getTime()));
        if (m_curInventoryBuffer.nReadRate > 0) {
            //rate by lei.li

            mTagsOpTimeText.setText(String
                    .valueOf(m_curInventoryBuffer.nDataCount * 1000
                            / m_curInventoryBuffer.nReadRate));
        } else {
            mTagsOpTimeText.setText("0");
        }
        mTagRealList.refreshText();
    }

    private final BroadcastReceiver mRecv = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ReaderHelper.BROADCAST_REFRESH_FAST_SWITCH)) {

            } else if (intent.getAction().equals(ReaderHelper.BROADCAST_REFRESH_INVENTORY)) {

            } else if (intent.getAction().equals(ReaderHelper.BROADCAST_REFRESH_INVENTORY_REAL)) {

            } else if (intent.getAction().equals(ReaderHelper.BROADCAST_REFRESH_ISO18000_6B)) {

            } else if (intent.getAction().equals(ReaderHelper.BROADCAST_REFRESH_OPERATE_TAG)) {

            } else if (intent.getAction().equals(ReaderHelper.BROADCAST_REFRESH_READER_SETTING)) {
                byte btCmd = intent.getByteExtra("cmd", (byte) 0x00);
                //mViewSetting.refreshReaderSetting(btCmd);
            } else if (intent.getAction().equals(ReaderHelper.BROADCAST_WRITE_LOG)) {
                //mLogList.writeLog((String)intent.getStringExtra("log"), intent.getIntExtra("type", ERROR.SUCCESS));
            }
        }
    };

    @Override
    protected void onResume() {
        if (mReader != null) {
            if (!mReader.IsAlive())
                mReader.StartWait();
        }
        super.onResume();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            askForOut();

            return true;
        } else if (keyCode == KeyEvent.KEYCODE_MENU) {
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }


    public void askForOut() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setTitle(getString(R.string.alert_diag_title)).
                setMessage(getString(R.string.are_you_sure_to_exit)).
                setPositiveButton(getString(R.string.ok),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //close the module
                                ModuleManager.newInstance().setUHFStatus(false);
                                getApplication().onTerminate();
                            }
                        }).setNegativeButton(getString(R.string.cancel),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                }).setCancelable(false).show();
    }
}
